class MyEventBus{
  constructor(){
    // 初始化消息队列 同 _events
    this.msgQueue = {};
  }
  on(event,fn){
    if(this.msgQueue.hasOwnProperty(event)){
      if(this.msgQueue[event] === 'function'){
        this.msgQueue[event] = [this.msgQueue[event],fn];
      }else{
        this.msgQueue[event] = [...this.msgQueue[event],fn];
      }
    }else{
      // 初始化的时候不直接使用数组，如果只有一个方法就减少了空间开销
      this.msgQueue[event] = fn;
    }
  }
  // 消息队列中只保存一个消息
  once(event,fn){
    // 无效检查event是否存在
    this.msgQueue[event] = fn;
  }
  // 发送消息
  emit(event,...msg){
    if(!this.msgQueue.hasOwnProperty(event)) return;
    try{
      if(typeof this.msgQueue[event] === 'function'){
        this.msgQueue[event](...msg);
      }else{
        this.msgQueue[event].map(fn=>{
          fn(...msg)
        })
      }
    }catch(e){
      console.log(e);
    }
  }
  // 移除消息
  off(event){
    if(!this.msgQueue.hasOwnProperty(event)) return;
    delete this.msgQueue[event]
  }
}

/**
 * 使用 EventBus
 * 也可以导出使用
 * const EventBus = new MyEventBus();
 * export default EventBus; 这样保证共享一个实例
 */
const EventBus = new MyEventBus();
EventBus.on('event1',(...msg)=>{console.log('订阅的消息是',msg)});
EventBus.emit('event1','hello world','123');
EventBus.off('event1');
EventBus.emit('event1','hello2world');